//获取节点
var carousel = document.getElementsByClassName('carousel')[0]
var slide = carousel.getElementsByClassName('slide')[0]
var slideItems = slide.getElementsByClassName('slide-item')

//轮播容器的宽度
var clientWidth = carousel.clientWidth;
var clientHeight= carousel.clientHeight
//复制第一张图片插入到末尾
slide.appendChild(slide.firstElementChild.cloneNode(true))

slide.style.width = clientWidth * slide.childElementCount + "px"
for (var i = 0; i < slideItems.length; i++) {
    slideItems[i].style.width = clientWidth + "px"
    slideItems[i].style.height = clientHeight + "px"
}

//图片过渡
slide.style.transition = "left 300ms linear"

//轮播下标
var index = 0
function moveLeft(){
    index++;
    switchIndicator()
    if (index == slideItems.length - 1){
        slide.style.left = -index * clientWidth + 'px';
        setTimeout(function () {
            //取消过渡效果
            slide.style.transition = '';
            index = 0;
            switchIndicator();
            slide.style.left = -index * clientWidth + 'px';
        setTimeout(function (){
                slide.style.transition= 'left 300ms linear'
            },20)
        },300)
    }else{
        slide.style.left = -index * clientWidth + 'px';
    }
}

//设置右移动
function moveRight(){
    index--;
    switchIndicator()
    if (index == 0){
        slide.style.left = -index * clientWidth + 'px';
        setTimeout(function () {
            //取消过渡效果
            slide.style.transition = '';
            index = 3;
            switchIndicator()
            slide.style.left = -index * clientWidth + 'px';
            setTimeout(function (){
                slide.style.transition= 'left 300ms linear'
            },20)
        },300)
    }else{
        slide.style.left = -index * clientWidth + 'px';
    }
}
//添加时钟事件
var timer ;
timer = setInterval(moveLeft,1000)

//左右按钮
var leftBtn= document.getElementsByClassName('left-btn')[0]
var rightBtn= document.getElementsByClassName('right-btn')[0]

leftBtn.onclick =function (){
    clearInterval(timer)
    moveLeft();
    timer = setInterval(moveLeft,1000)
}

rightBtn.onclick =function (){
    clearInterval(timer)
    moveRight();
    timer = setInterval(moveRight,1000)
}

function switchIndicator(){
    var items= document.getElementsByClassName('indicator')[0].
    getElementsByClassName('item')
    for (var i = 0; i < items.length; i++) {
if(i === index){
    items[i].className='item active'
}else {
    items[i].className='item'
}
    }
}

